package com.yupi.yurpc.server.tcp;

import com.yupi.yurpc.server.HttpServer;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;

public class VertxTcpServer implements HttpServer {

    private byte[] handleRequest(byte[] bytes) {
        //根据实际需求构建返回
        return "Hello Client".getBytes();
    }

    @Override
    public void doStart(int port) {
        Vertx vertx = Vertx.vertx();

        NetServer server = vertx.createNetServer();

        server.connectHandler(socket -> {

            socket.handler(buffer -> {
                //处理得到的字节数组
                byte[] bytes = buffer.getBytes();
                // 自定义字节数组处理逻辑
                byte[] response = handleRequest(bytes);

                //发送响应
                socket.write(Buffer.buffer(response));

            });
        });
        server.listen(port,result ->{
            if(result.succeeded()){
                System.out.println("Server started on port " + port);
            }else{
                System.out.println("Failed to start server: " + result.cause());
            }
        });
    }

    public static void main(String[] args) {
        new VertxTcpServer().doStart(8888);
    }
}
